package com.mission.schedule.service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;


import org.json.JSONArray;
import org.json.JSONObject;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.Request.Method;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.mission.schedule.applcation.App;
import com.mission.schedule.bean.AddTagBackBean;
import com.mission.schedule.bean.AddTagBean;
import com.mission.schedule.bean.TagBackBean;
import com.mission.schedule.bean.TagBean;
import com.mission.schedule.bean.TagCommandBean;
import com.mission.schedule.bean.TagDelBean;
import com.mission.schedule.constants.ShareFile;
import com.mission.schedule.constants.URLConstants;
import com.mission.schedule.cutimage.Log;
import com.mission.schedule.utils.SharedPrefUtil;
import com.mission.schedule.utils.StringUtils;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;

/**
 * 标签下载同步
 */
public class UpdataTagService extends Service {

    List<TagCommandBean> addList = new ArrayList<TagCommandBean>();
    List<TagCommandBean> updateList = new ArrayList<TagCommandBean>();
    List<TagCommandBean> deleteList = new ArrayList<TagCommandBean>();
    String json;
    String userid;
    SharedPrefUtil sharedPrefUtil = null;
    App app = App.getDBcApplication();
    public static List<AddTagBean> tagbeans = null;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
        tagbeans = new ArrayList<AddTagBean>();
        sharedPrefUtil = new SharedPrefUtil(getApplication(), ShareFile.USERFILE);
        userid = sharedPrefUtil.getString(getApplication(), ShareFile.USERFILE, ShareFile.USERID, "0");
        if (sharedPrefUtil.getString(getApplication(),
                ShareFile.USERFILE, ShareFile.ISNEWYOUKE, "0").equals("-1")) {
            if (intent != null) {
                if (intent.getStringExtra("down").equals("downtag")) {
                    downTag();
                } else {
                    updateLoad();
                }
            } else {
                updateLoad();
            }
        }
    }

    private void updateLoad() {
        if (sharedPrefUtil.getString(getApplication(), ShareFile.USERFILE, ShareFile.ISNEWYOUKE, "0").equals("-1")) {
            addList.clear();
            updateList.clear();
            deleteList.clear();
            JSONArray jsonarray1 = new JSONArray();
            JSONArray jsonarray2 = new JSONArray();
            JSONArray jsonarray3 = new JSONArray();
            JSONObject jsonobject1 = new JSONObject();
            try {
                addList = app.QueryTagData(1);
                updateList = app.QueryTagData(2);
                deleteList = app.QueryTagData(3);
            } catch (Exception e) {
                e.printStackTrace();
            }

            if (addList.size() > 0 || updateList.size() > 0 || deleteList.size() > 0) {
                try {
                    if (addList != null && addList.size() > 0) {
                        for (int i = 0; i < addList.size(); i++) {
                            JSONObject jsonobject = new JSONObject();
                            jsonobject.put("id", addList.get(i).getCtgId());
                            jsonobject.put("tagName", addList.get(i).getCtgText());
                            jsonobject.put("uid", userid);
                            jsonobject.put("stateTag", addList.get(i).getCtgType());
                            jsonobject.put("remark", addList.get(i).getCtgDesc());
                            jsonobject.put("orderIndex", addList.get(i).getCtgOrder());
                            jsonobject.put("color", addList.get(i).getCtgColor());
                            jsonarray1.put(jsonobject);
                        }
                        jsonobject1.put("addData", jsonarray1);
                    } else {
                        jsonobject1.put("addData", jsonarray1);
                    }
                    if (updateList != null && updateList.size() > 0) {
                        for (int i = 0; i < updateList.size(); i++) {
                            JSONObject jsonobject = new JSONObject();
                            jsonobject.put("id", updateList.get(i).getCtgId());
                            jsonobject.put("tagName", updateList.get(i).getCtgText());
                            jsonobject.put("uid", userid);
                            jsonobject.put("stateTag", updateList.get(i).getCtgType());
                            jsonobject.put("remark", updateList.get(i).getCtgDesc());
                            jsonobject.put("orderIndex", updateList.get(i).getCtgOrder());
                            jsonobject.put("color", updateList.get(i).getCtgColor());
                            jsonarray2.put(jsonobject);
                        }
                        jsonobject1.put("updateData", jsonarray2);
                    } else {
                        jsonobject1.put("updateData", jsonarray2);
                    }
                    if (deleteList != null && deleteList.size() > 0) {
                        for (int i = 0; i < deleteList.size(); i++) {
                            JSONObject jsonobject = new JSONObject();
                            jsonobject.put("id", deleteList.get(i).getCtgId());
                            jsonobject.put("tagName", deleteList.get(i).getCtgText());
                            jsonobject.put("uid", userid);
                            jsonobject.put("stateTag", deleteList.get(i).getCtgType());
                            jsonobject.put("remark", deleteList.get(i).getCtgDesc());
                            jsonobject.put("orderIndex", deleteList.get(i).getCtgOrder());
                            jsonobject.put("color", deleteList.get(i).getCtgColor());
                            jsonarray3.put(jsonobject);
                        }
                        jsonobject1.put("deleData", jsonarray3);
                    } else {
                        jsonobject1.put("deleData", jsonarray3);
                    }

                    json = jsonobject1.toString();
                    String path = URLConstants.新标签新增;
                    StringRequest request = new StringRequest(Method.POST, path, new Response.Listener<String>() {

                        @Override
                        public void onResponse(String s) {
                            if (!TextUtils.isEmpty(s)) {
                                Gson gson = new Gson();
                                try {
                                    AddTagBackBean backBean = gson.fromJson(s, AddTagBackBean.class);
                                    List<AddTagBean> beans = null;
                                    if (backBean.status == 0) {
                                        beans = backBean.list;
                                        if (beans != null && beans.size() > 0) {
                                            for (int i = 0; i < beans.size(); i++) {
                                                if (beans.get(i).state == 0) {
                                                    if (beans.get(i).dataState == 0) {
                                                        app.updateTagID(beans.get(i).originalId, beans.get(i).id);
                                                    } else if (beans.get(i).dataState == 1) {
                                                        app.updateTagID(beans.get(i).id, beans.get(i).id);
                                                    } else if (beans.get(i).dataState == 2) {
                                                        app.deleteTagData(beans.get(i).id);
                                                    }
                                                }
                                            }
                                        }
                                    } else {
                                        stopSelf();
                                    }
                                } catch (JsonSyntaxException e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    }, new Response.ErrorListener() {

                        @Override
                        public void onErrorResponse(VolleyError arg0) {
                            stopSelf();
                            App.getHttpQueues().cancelAll("updatetag");
                        }

                    }) {
                        @Override
                        protected Map<String, String> getParams()
                                throws AuthFailureError {
                            Map<String, String> map = new HashMap<String, String>();
                            map.put("data", json);
                            return map;
                        }
                    };
                    request.setTag("updatetag");
                    request.setRetryPolicy(new DefaultRetryPolicy(20000, 1, 1.0f));
                    App.getHttpQueues().add(request);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                downTag();
            }
        }
    }

    /**
     * 下载新标签
     */

    String[] emptyTag = {"生活","工作","理财","其它","分类A","分类B"};
    private void downTag() {
        final App app = App.getDBcApplication();
        String downtagtime = sharedPrefUtil.getString(getApplication(), ShareFile.USERFILE, ShareFile.DOWNTAGDATE, "2016-01-01%2B00:00:00");
        if (downtagtime.isEmpty()) {
            downtagtime = "2016-01-01%2B00:00:00";
        }
        String downtagpath = URLConstants.标签下载 + userid + "&changeTime=" + downtagtime;
        StringRequest request = new StringRequest(Method.GET,
                downtagpath, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                if (!TextUtils.isEmpty(s)) {
                    try {
                        List<TagBean> tagBeans;
                        List<TagDelBean> delBeans;
                        Gson gson = new Gson();
                        TagBackBean backBean = gson.fromJson(s, TagBackBean.class);
                        if (backBean.status == 0) {
                            sharedPrefUtil.putString(getApplication(), ShareFile.USERFILE, ShareFile.DOWNTAGDATE, backBean.downTime.replace("T", "%2B"));
                            tagBeans = backBean.list;
                            delBeans = backBean.delList;
                            if (tagBeans != null && tagBeans.size() > 0) {
                                for (Iterator<TagBean> item = tagBeans.iterator(); item.hasNext(); ) {
                                    TagBean it = item.next();
                                    if (it.uid == 0) {
                                        item.remove();
                                    }
                                }
                                HashSet<TagBean> hashSet = new HashSet<>(tagBeans);
                                tagBeans.clear();
                                tagBeans.addAll(hashSet);

                                Collections.sort(tagBeans, new Comparator<TagBean>() {
                                    @Override
                                    public int compare(TagBean lhs, TagBean rhs) {
                                        if (lhs.orderIndex > rhs.orderIndex){
                                            return 1;
                                        } else if (lhs.orderIndex == rhs.orderIndex) {
                                            return 0;
                                        }else {
                                            return -1;
                                        }
                                    }
                                });
                                if (tagBeans.size() >= 6){
                                    for (int i = 0; i < 6; i++){
                                        TagBean tagBean = tagBeans.get(i);
                                        String tagtext = "";
                                        String ctgColor = "0";
                                        if (!StringUtils.getIsStringEqulesNull(tagBean.tagName).isEmpty()) {
                                            tagtext = tagBean.tagName;
                                        }
                                        if (!StringUtils.getIsStringEqulesNull(tagBean.color).isEmpty()) {
                                            ctgColor = tagBean.color;
                                        }
                                        app.insertTagIntenetData(tagBean.id, tagtext, tagBean.orderIndex, ctgColor, tagBean.stateTag, 0, tagBean.remark, "");
                                    }
                                    app.insertTagIntenetData(101, "生日", 0, "0", 0, 0, "1", "");
                                } else {
                                    int tagSize = 6 - tagBeans.size();
                                    int b = 1;
                                    for (TagBean tagBean : tagBeans) {
                                        String tagtext = "";
                                        String ctgColor = "0";
                                        if (!StringUtils.getIsStringEqulesNull(tagBean.tagName).isEmpty()) {
                                            tagtext = tagBean.tagName;
                                        }
                                        if (!StringUtils.getIsStringEqulesNull(tagBean.color).isEmpty()) {
                                            ctgColor = tagBean.color;
                                        }
                                        app.insertTagIntenetData(tagBean.id, tagtext, tagBean.orderIndex, ctgColor, tagBean.stateTag, 0, b+"", "");
                                        b++;
                                    }
                                    for (int i = 0; i < 6; i++){
                                        if (i >= (6 - tagSize)){
                                            app.insertTagIntenetData(-(i + 1), emptyTag[i], i + 1, "0", 1, 1, ""+(i + 2), "");
                                        }
                                    }
                                    app.insertTagIntenetData(101, "生日", 0, "0", 0, 0, "1", "");
                                    updateLoad();
                                }
                            }else {
                                addTga();
                            }
                            if (delBeans != null && delBeans.size() > 0) {
                                for (int i = 0; i < delBeans.size(); i++) {
                                    try {
                                        int count = app.CheckCountTagData(Integer.parseInt(delBeans.get(i).dataId));
                                        if (count != 0) {
                                            app.deleteTagData(Integer.parseInt(delBeans.get(i).dataId));
                                        }
                                    } catch (NumberFormatException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }
                        }else{
                            addTga();
                        }
                    } catch (JsonSyntaxException e) {
                        e.printStackTrace();
                        addTga();
                    }
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                addTga();
            }
        });
        request.setTag("downtag");
        request.setRetryPolicy(new DefaultRetryPolicy(10000, 1, 1.0f));
        App.getHttpQueues().add(request);
    }

    private void addTga(){
        app.insertTagIntenetData(101, "生日", 0, "0", 0, 0, "1", "");
        for (int i = 0; i < emptyTag.length ; i++){
            App.getDBcApplication().insertTagIntenetData(-(i + 1), emptyTag[i], i + 1, "0", 1, 1, ""+(i + 2), "");
        }
        updateLoad();
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        stopSelf();
        App.getHttpQueues().cancelAll("updatetag");
    }
}
